// 本文件主要进行订单相关数据的清洗
package order

import (
	"context"
	"encoding/json"
	"sale-admin/internal/dal"
	"sale-admin/internal/dao"
	"sale-admin/internal/models"
)

type OrderDataFix struct{}

// BackfillGoodsID 回填订单表商品信息字段的值
func (OrderDataFix) BackfillGoodsID(ctx context.Context, startTime, endTime int64) {
	orderList, _ := dao.NewOrder(context.Background(), dal.Q).
		WithTimePeriodCond(startTime, endTime).
		List()
	for _, orderRecord := range orderList {
		// 解析订单记录的CountData数据，获取商品id和商品单价
		var goodsInfoStruct []struct {
			GoodsID   string  `json:"GoodsID"`   // 商品id
			Univalent float64 `json:"Univalent"` // 商品单价
		}
		goodsInfoString := orderRecord.CountData
		json.Unmarshal([]byte(goodsInfoString), &goodsInfoStruct)
		// 回填订单的goods_id和goods_price字段
		if len(goodsInfoStruct) > 0 {
			dao.NewOrder(context.Background(), dal.Q).
				WithOrderIDCond([]string{orderRecord.OrderID}).
				Update(models.MaOrder{
					GoodsID: goodsInfoStruct[0].GoodsID,
				})
		}
	}
}

// FixOrderAddTime 修正订单的创建时间
func (OrderDataFix) FixOrderAddTime(ctx context.Context, startTime, endTime int64) {
	orderList, _ := dao.NewOrder(context.Background(), dal.Q).
		GroupByOutTradeNo().
		WithTimePeriodCond(startTime, endTime).
		List()
	for _, orderRecord := range orderList {
		var record models.MaOrder
		record.AddTime = orderRecord.AddTime
		record.CreatedAt = orderRecord.CreatedAt
		dao.NewOrder(ctx, dal.Q).WithOutTradeNoCond(orderRecord.OutTradeNo).Update(record)
	}
}
